package main

import (
	"fmt"
	"io"
	"net/http"
	"sync"
	"time"
)

/*
下载器：并发执行IO密集型任务
*/
func downloader(url string, ch chan<- string, wg *sync.WaitGroup) {
	defer wg.Done()

	start := time.Now()

	// 模拟下载
	resp, err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprintf("下载失败 %s: %v", url, err)
		return
	}
	defer resp.Body.Close()

	// 读取内容长度
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		ch <- fmt.Sprintf("读取失败 %s: %v", url, err)
		return
	}

	duration := time.Since(start)
	ch <- fmt.Sprintf("下载成功 %s: 大小 %d bytes, 耗时 %v", url, len(body), duration)
}

func main() {
	urls := []string{
		"https://httpbin.org/delay/1",
		"https://httpbin.org/delay/2",
		"https://httpbin.org/delay/1",
		"https://httpbin.org/status/404",
		"https://httpbin.org/delay/3",
	}

	results := make(chan string, len(urls))
	var wg sync.WaitGroup

	fmt.Println("开始并发下载...")

	// 启动下载任务
	for _, url := range urls {
		wg.Add(1)
		go downloader(url, results, &wg)
	}

	// 等待所有下载完成并关闭channel
	go func() {
		wg.Wait()
		close(results)
	}()

	// 显示结果
	fmt.Println("\n=== 下载结果 ===")
	for result := range results {
		fmt.Println(result)
	}
}
